package cn.tedu.yl.TCLX.service;

import cn.tedu.yl.TCLX.mapper.TypeMapper;
import cn.tedu.yl.TCLX.pojo.Type;
import cn.tedu.yl.TCLX.pojo.nxtc;
import cn.tedu.yl.base.response.PageData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TypeService {

    @Autowired
    private TypeMapper typeMapper;
    @Qualifier("nxtcMapper")
    @Autowired
    private cn.tedu.yl.TCLX.mapper.nxtcMapper nxtcMapper;

    public PageData getAll() {
        PageData pageData = new PageData();
        pageData.setList(finAll());
        pageData.setTotal(typeMapper.findAll().size());
        return pageData;
    }

    private List finAll() {
        List<Type> all = typeMapper.findAll();

        for (Type type : all) {
            try {
                int typeId = Math.toIntExact(type.getId());
                List<nxtc> byTclxId = nxtcMapper.findByTclxId(typeId);
                type.setTotal(byTclxId.size());

                if (!byTclxId.isEmpty()) {
                    StringBuilder containBuilder = new StringBuilder();
                    for (nxtc nxtc : byTclxId) {
                        if (containBuilder.length() > 0) {
                            containBuilder.append(", ");
                        }
                        containBuilder.append(nxtc.getContainName());
                    }
                    type.setContain(containBuilder.toString());
                } else {
                    type.setContain(""); // 如果不需要设置为空字符串，可以删除这一行
                }
            } catch (ArithmeticException e) {
                // 处理异常，例如记录日志
                System.err.println("Error converting ID to int: " + e.getMessage());
            }
        }
        return all;
    }

    public void create(Type type) {
        typeMapper.save(type);
    }

    public void delete(Long id) {
        typeMapper.deleteById(id);
    }

    public void update(Long id, Type type) {

        Type type1 = typeMapper.findById(id).orElse(null);
        if (type1 != null){

            type1.setName(type.getName());
            type1.setTotal(type.getTotal());
            type1.setContain(type.getContain());
            type1.setStatus(type.getStatus());
            typeMapper.save(type1);
        }

    }
}
